package com.yaoxun.bored.controller.sys;

import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.yaoxun.bored.common.JsonObject;
import com.yaoxun.bored.model.sys.authority.Authority;
import com.yaoxun.bored.model.sys.authority.RoleConfig;
import com.yaoxun.bored.service.sys.authority.AuthorityService;
import com.yaoxun.bored.util.enums.MenuLeaf;

@Controller
@RequestMapping("/authority")
public class AuthorityController {

	private static final String INDEX_PAGE = "sys/authority/authority";
	
	@Inject
	private AuthorityService authorityService;
	
	
	@RequestMapping("/index")
	public ModelAndView index(@RequestParam Integer roleId) {
		ModelAndView mv = new ModelAndView(INDEX_PAGE);
		List<Authority> authorities = authorityService.selectMenu();
		for(Authority a : authorities) {
			if(a.getLeaf() == MenuLeaf.IS_LEAF.value()) {
				List<Authority> auths = authorityService.selectAuthByMenuId(a.getId());
				a.setAuthorities(auths);
			}
		}
		mv.addObject("authorities", authorities);
		mv.addObject("roleId", roleId);
		return mv;
	}
	
	@RequestMapping(value="/config", method=RequestMethod.GET)
	@ResponseBody
	public RoleConfig config(@RequestParam Integer roleId) {
		RoleConfig roleConfig = authorityService.getRoleConfig(roleId);
		return roleConfig;
	}
	
	@RequestMapping(value="/config", method=RequestMethod.POST)
	@ResponseBody
	public JsonObject config(@RequestParam Integer roleId, 
			@RequestParam("menuIds[]") Integer[] menuIds,
			@RequestParam("authIds[]") Integer[] authIds) {
		JsonObject jsonObject = new JsonObject();
		RoleConfig config = new RoleConfig(roleId, menuIds, authIds);
		authorityService.config(config);
		return jsonObject;
	}
	
	
}
